package tk.djcrazy.instantmessage.action;

import java.util.Map;

import org.apache.struts2.interceptor.SessionAware;

import tk.djcrazy.instantmessage.domain.LoginState;
import tk.djcrazy.instantmessage.domain.UserEntity;
import tk.djcrazy.instantmessage.service.IUserService;
import tk.djcrazy.instantmessage.service.IUserStateService;

import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport implements SessionAware {
	private String userName;
	private String password;
	private Map<String, Object> session;
	private IUserService userService;
	private static final long serialVersionUID = -8718104687043569651L;

	private IUserStateService userStateService;

	@Override
	public String execute() {
		return INPUT;
	}

	public String login() {
		try {
			if (userService.authenticateUser(userName, password)) {
				UserEntity entity = userService.findByUserName(userName);
				session.put("uid", entity.getId());
				session.put("userName", entity.getUserName());
				session.put("avatar", entity.getAvatarPath());
				userStateService.changeLoginState(entity.getId(),
						LoginState.ON_LINE);
				return SUCCESS;
			}
			addActionError("用户名或密码错误！");
			return INPUT;
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
	}

	public String logout() {
		userStateService.changeLoginState((Integer) session.get("uid"),
				LoginState.OFF_LINE);
		session.clear();
		return SUCCESS;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public Map<String, Object> getSession() {
		return session;
	}

	public void setSession(Map<String, Object> session) {
		this.session = session;
	}

	public IUserService getUserService() {
		return userService;
	}

	public void setUserService(IUserService userService) {
		this.userService = userService;
	}

	public IUserStateService getUserStateService() {
		return userStateService;
	}

	public void setUserStateService(IUserStateService userStateService) {
		this.userStateService = userStateService;
	}
}
